const CACHE_NAME = 'api-stats-v1';

self.addEventListener('install', (event) => {
  self.skipWaiting();
});

self.addEventListener('activate', (event) => {
  event.waitUntil(self.clients.claim());
});

// Stale-While-Revalidate for /api/stats (including query)
self.addEventListener('fetch', (event) => {
  const { request } = event;
  if (request.method !== 'GET') return;
  const url = request.url || '';
  if (!url.includes('/api/stats')) return;

  event.respondWith((async () => {
    const cache = await caches.open(CACHE_NAME);
    const cached = await cache.match(request);
    const fetchPromise = fetch(request)
      .then((networkResponse) => {
        // Only cache 200 responses
        if (networkResponse && networkResponse.status === 200) {
          cache.put(request, networkResponse.clone());
        }
        return networkResponse;
      })
      .catch(() => cached);

    // Return cached immediately if available; otherwise wait for network
    return cached || fetchPromise;
  })());
});

